#include "DirScanner.hh"
#include <iostream>
#include <vector>
#include <string>
#include <dirent.h>

//class DirScanner;

DirScanner::DirScanner()
{}

void DirScanner::operator()() // 重载函数调用运算符，调用 traverse 函数
{
    traverse("../conf/人民网语料");
}

void DirScanner::traverse(const string& dirname)// 获取某一目录下的所有文件
{
    DIR* dir;
    struct dirent* entry;
    char str[1024];
    //int j=0;
    getcwd(str,sizeof(str));
    int i=strlen(str)-4;
    if ((dir = opendir(dirname.c_str())) != nullptr) {
        while ((entry = readdir(dir)) != nullptr) {
            std::string filename(entry->d_name);

            // 忽略当前目录和上级目录的项
            if (filename != "." && filename != "..") {
                string path = dirname + "/" + filename;

                // 判断是否为普通文件
                if (entry->d_type == DT_REG) {
                    getcwd(str,sizeof(str));
                    str[i]=0;
                    strcat(str,"/");
                    path=path.substr(3,1024);
                    path=str+path;
                    
                    _files.push_back(path);
                    //cout<<j++<<endl;
                }

                // 判断是否为目录，递归调用
                if (entry->d_type == DT_DIR) {
                    //traverse(path);
                }
            }
        }
       
        closedir(dir);
    }
}

vector<string>& DirScanner::files()  //接口，调用返回_files
{
    return _files;
}


#if 0//测试
int main() {
    //std::string dirname = "../tinyxml2-master";
    std::vector<std::string> files;
    DirScanner l1;
    l1();

    l1.get();

    // 输出获取到的文件路径
    //for (const auto& file :files) {
      //  std::cout << file << std::endl;
    //}
    
    return 0;
}
#endif



